package com.runen.wnhz.runen.ui.activity.mine;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.google.gson.Gson;
import com.runen.wnhz.runen.R;
import com.runen.wnhz.runen.common.utils.ACacheUtlis;
import com.runen.wnhz.runen.common.utils.NetUtils;
import com.runen.wnhz.runen.common.utils.OkHttpUtils;
import com.runen.wnhz.runen.common.utils.ToastUtil;
import com.runen.wnhz.runen.data.entity.MyEvaluationBean;
import com.runen.wnhz.runen.data.entity.MyQuestionBean;
import com.runen.wnhz.runen.data.entity.UserBean;
import com.runen.wnhz.runen.di.component.ApplicationComponent;
import com.runen.wnhz.runen.presenter.Contart.QuestionBankContart;
import com.runen.wnhz.runen.presenter.iPresenter.IEvaluationPersenter;
import com.runen.wnhz.runen.ui.activity.BaseActivity;
import com.runen.wnhz.runen.ui.activity.XFormattedValue;
import com.runen.wnhz.runen.ui.activity.login.LoginForPersonalActivity;
import com.runen.wnhz.runen.widget.TitleBuilder;
import com.runen.wnhz.runen.widget.chart.BarChart2Class;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by Administrator on 2018-04-12.
 */

public class TestRecordActivity extends BaseActivity<IEvaluationPersenter> implements QuestionBankContart.View {

    @BindView(R.id.chart)
    BarChart chart;

    List<String> dayList;

    private UserBean reqeustUser;
    private List<String> dateList;
    private List<Float> scoreList;

    BarChart2Class barChart2Class;
    String ltid;

    private List<Integer> numbers = new ArrayList<>();
    private int number;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected int getLayoutView() {
        return R.layout.test_record_activity_layout;
    }

    @Override
    protected void onTitleClickListen(TitleBuilder.TitleButton clicked) {
        switch (clicked) {
            case LEFT:
                finish();
                break;
            case MIDDLE:
                break;
            case RIGHT:
                break;
            default:
                break;
        }
    }

    @Override
    protected void initStart() {
        ltid = getIntent().getStringExtra("ltid");
        /*setData();*/
        getLearningLessonData(ltid);
       /* getLearningLessonData(ltid);
        initBarChartStyle(chart);*/
    }

    @Override
    public void initToolBar(TitleBuilder mTitleBuilder) {
        mTitleBuilder.setMiddleTitleText("测试记录")
                .setLeftDrawable(R.mipmap.icon_back)
                .seTitleBgRes(R.mipmap.bg_title)
                .setMiddleTitleTextColor(ContextCompat.getColor(this, R.color.text_white));
    }

    @Override
    public void setupAcitivtyComponent(ApplicationComponent appComponent) {

    }

    private void getLearningLessonData(String ltid) {
        if (getToken() != null) {
            FormBody formBody = new FormBody.Builder().add("token", getToken()).add("ltid", ltid).build();
            Request request = new Request.Builder().url(NetUtils.TEST_MYTestLog).post(formBody).build();
            Call newCall = OkHttpUtils.getOkHttpClient().newCall(request);
            newCall.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                   runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast("数据请求失败");
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try {
                        handleUserLesson(response);
                    } catch (IOException e) {
                        e.printStackTrace();
                       runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtil.showToast("数据请求出现异常");
                            }
                        });
                    }
                }
            });
        }
    }


    private void handleUserLesson(Response response) throws IOException {
        if (response.isSuccessful()) {
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                final String json = responseBody.string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        MyQuestionBean evaluationEntity = new Gson().fromJson(json, MyQuestionBean.class);
                        if (evaluationEntity != null) {
                            if ("1".equals(evaluationEntity.getRe())) {
                                List<MyQuestionBean.DataBean.ListBean> list = evaluationEntity.getData().getList();
                                if(list.size() > 0 ){
                                    int getOp = list.size();
                                    if( list.size()>3){
                                        getOp = 3;
                                    }

                                    ArrayList<BarEntry> barEntriesData = new ArrayList<>();

                                    Random random = new Random();

                                    dateList = new ArrayList<>();
                                    scoreList = new ArrayList<>();
                                    for(int i=1;i<=getOp;i++){
                                        dateList.add(list.get(i).getAddtime());
                                        scoreList.add(Float.valueOf(list.get(i).getScore()));
                                        barEntriesData.add(new BarEntry(i,Float.valueOf(list.get(i).getScore())));
                                        numbers.add(number);
                                    }

                                    //2，BarDataSet
                                    BarDataSet bardataSet = new BarDataSet(barEntriesData,"");
                                    bardataSet.setDrawValues(true);//设置柱状图顶部显示数值

                                    //3，把BarDataSet数据添加到IBarDataSet集合
                                    ArrayList<IBarDataSet> iBarDataSets = new ArrayList<>();
                                    iBarDataSets.add(bardataSet);

                                    //4,BarData
                                    BarData barData = new BarData(iBarDataSets);
                                    //5,设置数据
                                    chart.setData(barData);
                                    setChart();

                                /*    List<BarEntry> barEntries = new ArrayList<>();

                                   if(barEntries!=null){
                                       barEntries.clear();
                                   }
                                    for(int i=0 ; i<getOp ;  i++){
                                       String monthandday = list.get(i).getAddTime();
                                      barEntries.add(new BarEntry(i,Float.parseFloat(list.get(i).getScore())));
                                    }
                                   BarDataSet barDataSet = new BarDataSet(barEntries, "成绩表");
                                   barDataSet.setDrawValues(false);

                                   ArrayList<IBarDataSet> iBarDataSets = new ArrayList<>();
                                   iBarDataSets.add(barDataSet);

                                   BarData barData = new BarData(iBarDataSets);

                                *//*    barDataSet.setColor(Color.parseColor("#FF594B21"));
                                    barDataSet.setFormLineWidth(1f);
                                    barDataSet.setFormSize(15.f);
                                    barData.setBarWidth(0.5f);*//*
                                    chart.setData(barData);*/
                                }
                                    return;
                                }

                             else if (evaluationEntity.getRe().equals("0")) {
                                ToastUtil.showToast(evaluationEntity.getInfo());
                            } else if (evaluationEntity.getRe().equals("-1")) {
                                ToastUtil.showToast(evaluationEntity.getInfo());
                                startActivity(new Intent(TestRecordActivity.this, LoginForPersonalActivity.class));
                            }
                        }
                    }
                });

            }
        }
    }
    @Override
    public String getPage() {
        return null;
    }

    @Override
    public String getToken() {
        reqeustUser = ACacheUtlis.getInstance().getReqeustUser(this);
        return reqeustUser.getToken();
    }

    @Override
    public void onSuccess(MyQuestionBean data) {

    }


    private void initBarChartStyle(BarChart mBarChart) {
        mBarChart.animateY(2000);   //从Y轴进入的动画
/*        List<BarEntry> barEntries = new ArrayList<>();
        barEntries.add(new BarEntry(2000, 20));
        barEntries.add(new BarEntry(2001, 30));
        barEntries.add(new BarEntry(2002, 10));
        barEntries.add(new BarEntry(2003, 40));

        BarDataSet barDataSet = new BarDataSet(barEntries, "成绩表");
        BarData barData = new BarData(barDataSet);
        barDataSet.setColor(Color.parseColor("#FF594B21"));
        barDataSet.setFormLineWidth(1f);
        barDataSet.setFormSize(15.f);
        barData.setBarWidth(0.5f);*/

        Description description = new Description();
        description.setEnabled(false);
        mBarChart.setDescription(description);



        YAxis leftAxis = mBarChart.getAxisLeft();              //获取到y轴，分左右
        leftAxis.setLabelCount(10, false);                      //第一个参数是轴坐标的个数，第二个参数是 是否不均匀分布，true是不均匀分布
        leftAxis.setDrawGridLines(false);                      //不要横网格
        leftAxis.setGridColor(Color.parseColor("#000000"));   //设置横网格颜色
        leftAxis.setSpaceTop(20f);                            //设置在图表上最高处的值相比轴上最高值的顶端空间（总轴范围的百分比）
        leftAxis.setAxisMinimum(0f);                          //为这个轴设置一个自定义的最小值。如果设置,这个值不会自动根据所提供的数据计算
        leftAxis.setDrawLabels(true);          //显示Y轴上的刻度
        leftAxis.setTextColor(Color.BLACK);
        leftAxis.setDrawAxisLine(true);                      //设置为true,绘制轴线
        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);       //y轴的数值显示在外侧
        //这里也可以自定义y轴显示样式。和x轴的自定义方法一样
        mBarChart.getAxisRight().setEnabled(false); // 隐藏右边 的坐标轴
        Legend legend = mBarChart.getLegend();
        legend.setEnabled(false);//不设置图例

        //setAxisMaximum(float max)为这个轴设置一个自定义的最大值。如果设置,这个值不会自动根据所提供的数据计算
        //resetAxisMaximum()：撤销先前设置的最大值。通过这样做,你将再次允许轴自动计算它的最大值
//        Collections.sort(numbers);            //重新排序集合，按小到大排序
        leftAxis.setAxisMaximum( 100 );      //动态自定义y轴的最大值

        XAxis xAxis1 = mBarChart.getXAxis();
        leftAxis.setLabelCount(3, false);
        xAxis1.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis1.setDrawGridLines(false);
        xAxis1.setTextColor(Color.BLACK);
        mBarChart.getAxisRight().setEnabled(false);
        xAxis1.setValueFormatter(new XFormattedValue(TestRecordActivity.this,dateList,scoreList));


 /*       xAxis1.setGranularity(5f);//设置最小间隔，防止当放大时，出现重复标签。
        xAxis1.setLabelCount(4);//设置x轴显示的标签个数
        xAxis1.setAxisLineWidth(2f);//设置x轴宽度, ...其他样式*/

    /*    xAxis1.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float v, AxisBase axisBase) {
             *//*   String day = ""+ v;
                String nowday = day.substring(4,6)  + day.substring(6,8);*//*
                return (int)v +"";
            }
        });
        mBarChart.getAxisLeft().setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {

                return (int) value + "";
            }
        });
*/
/*        //给开头和结尾留空白
        mBarChart.setFitBars(true);
//        mBarChart.setData(barData);
        mBarChart.invalidate();*/
    }

    /*
     * 设置BarChart的数据
     * */
    private void setChart() {
        chart.setDescription(null);                          //设置描述文字为null
        chart.setBackgroundColor(Color.parseColor("#ffffff"));  //设置背景颜色
        chart.setDrawBarShadow(false);                          //绘制当前展示的内容顶部阴影
        chart.setPinchZoom(false);                              //设置x轴和y轴能否同时缩放。默认否

        chart.setMaxVisibleValueCount(10);                       //设置图表能显示的最大值，仅当setDrawValues()属性值为true时有用
        chart.setFitBars(true);                                 //设置X轴范围两侧柱形条是否显示一半


        XAxis xAxis = chart.getXAxis();                         //x轴
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);             //设置label在底下
        xAxis.setDrawGridLines(false);                             //不设置竖型网格线
        xAxis.setTextColor(Color.parseColor("#ffffff"));
        xAxis.setTextSize(8);
        xAxis.setDrawLabels(true);                                 //是否显示X坐标轴上的刻度，默认是true
        xAxis.setLabelCount(10,false);                             //第一个参数是轴坐标的个数，第二个参数是 是否不均匀分布，true是不均匀分布
        //至此，x坐标轴显示的是1,2,3,4,5,6,7,8,9,10
        //自定义x轴显示的数字格式
        xAxis.setValueFormatter(new XFormattedValue(TestRecordActivity.this,dateList,scoreList));

  /*      //自定义markView
        MyMarkView markerView = new MyMarkView(MainActivity.this,R.layout.my_marker_view);
        markerView.setChartView(chart);
        chart.setMarker(markerView);*/


        YAxis leftAxis = chart.getAxisLeft();              //获取到y轴，分左右
        leftAxis.setLabelCount(9, true);                      //第一个参数是轴坐标的个数，第二个参数是 是否不均匀分布，true是不均匀分布
        leftAxis.setDrawGridLines(false);                      //不要横网格
        leftAxis.setGridColor(Color.parseColor("#000000"));   //设置横网格颜色
        leftAxis.setSpaceTop(20f);                            //设置在图表上最高处的值相比轴上最高值的顶端空间（总轴范围的百分比）
        leftAxis.setAxisMinimum(0f);                          //为这个轴设置一个自定义的最小值。如果设置,这个值不会自动根据所提供的数据计算

        leftAxis.setTextColor(Color.WHITE);
        leftAxis.setDrawAxisLine(false);                      //设置为true,绘制轴线
        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);       //y轴的数值显示在外侧
        //这里也可以自定义y轴显示样式。和x轴的自定义方法一样
        chart.getAxisRight().setEnabled(false); // 隐藏右边 的坐标轴
        Legend legend = chart.getLegend();
        legend.setEnabled(false);//不设置图例

        //setAxisMaximum(float max)为这个轴设置一个自定义的最大值。如果设置,这个值不会自动根据所提供的数据计算
        //resetAxisMaximum()：撤销先前设置的最大值。通过这样做,你将再次允许轴自动计算它的最大值
        Collections.sort(numbers);            //重新排序集合，按小到大排序
        leftAxis.setAxisMaximum( 100 );      //动态自定义y轴的最大值

   /*     LimitLine limitLine  = new LimitLine(10.0f,"限制线：10.0");
        limitLine.setLabelPosition(LimitLine.LimitLabelPosition.LEFT_TOP);
        limitLine.setTextSize(8);
        limitLine.setTextColor(Color.parseColor("#000000"));
        leftAxis.addLimitLine(limitLine);*/

        chart.setTouchEnabled(false);
    }


    /*
     * 准备数据，Barchart设置数据
     * 设置数据需要四个步骤
     * */
    private void  setData(){
        //1,BarEntry集合,
        ArrayList<BarEntry> barEntriesData = new ArrayList<>();

        Random random = new Random();
        for(int i=1;i<=10;i++){
            barEntriesData.add(new BarEntry(i,number = random.nextInt(101)));
            numbers.add(number);
        }

        //2，BarDataSet
        BarDataSet bardataSet = new BarDataSet(barEntriesData,"");
        bardataSet.setDrawValues(true);//设置柱状图顶部显示数值

        //3，把BarDataSet数据添加到IBarDataSet集合
        ArrayList<IBarDataSet> iBarDataSets = new ArrayList<>();
        iBarDataSets.add(bardataSet);

        //4,BarData
        BarData barData = new BarData(iBarDataSets);
        //5,设置数据
        chart.setData(barData);
    }

}
